<template>
    <div class="edit-exam">
        <el-card class="edit-card">
            <template #header>
                <div class="card-header">
                    <h2>编辑考试gh</h2>
                    <el-button type="primary" @click="goBack">返回</el-button>
                </div>
            </template>
            <div class="edit-content" v-loading="loading">
                <el-form :model="examForm" :rules="rules" ref="examFormRef" label-width="100px">
                    <el-form-item label="考试名称" prop="examName">
                        <el-input v-model="examForm.examName" placeholder="请输入考试名称" />
                    </el-form-item>
                    <el-form-item label="考试科目" prop="subject">
                        <el-input v-model="examForm.subject" placeholder="请输入考试科目" />
                    </el-form-item>
                    <el-form-item label="开始时间" prop="startTime">
                        <el-date-picker
                            v-model="examForm.startTime"
                            type="datetime"
                            placeholder="选择开始时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item label="考试时长" prop="duration">
                        <el-input-number v-model="examForm.duration" :min="1" placeholder="请输入考试时长（分钟）" />
                    </el-form-item>
                    <el-form-item label="总分" prop="totalScore">
                        <el-input-number v-model="examForm.totalScore" :min="1" placeholder="请输入总分" />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="examForm.status" placeholder="请选择状态">
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmit">保存修改</el-button>
                        <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-form>

                <div class="questions-section">
                    <div class="section-header">
                        <h3>试题列表</h3>
                        <div class="question-actions">
                            <el-button type="primary" @click="showQuestionBankDialog">
                                <el-icon><Plus /></el-icon>
                                从题库添加试题
                            </el-button>
                        </div>
                    </div>
                    
                    <el-empty v-if="!examForm.questionList || examForm.questionList.length === 0" description="暂无试题" />
                    
                    <div v-else class="question-list">
                        <div v-for="(question, index) in examForm.questionList" :key="question.questionId" class="question-item">
                            <el-card class="question-card">
                                <div class="question-header">
                                    <span class="question-index">第{{ index + 1 }}题</span>
                                    <el-tag size="small" :type="getQuestionTypeTag(question.type)">{{ question.type }}</el-tag>
                                    <span class="question-score">{{ question.score }}分</span>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="handleDeleteQuestion(question)"
                                        class="delete-btn"
                                    >
                                        删除
                                    </el-button>
                                </div>
                                
                                <div class="question-content">
                                    <div class="content-text">{{ question.content }}</div>
                                    
                                    <!-- 选择题选项 -->
                                    <div v-if="['单选题', '多选题'].includes(question.type)" class="options">
                                        <template v-if="question.options">
                                            <div v-for="(option, idx) in parseOptions(question.options)" 
                                                 :key="idx" 
                                                 class="option-item"
                                                 v-show="option">
                                                <span class="option-label">{{ String.fromCharCode(65 + idx) }}.</span>
                                                <span class="option-content">{{ option }}</span>
                                            </div>
                                        </template>
                                    </div>
                                    
                                    <div class="question-answer">
                                        <div class="answer-label">参考答案：</div>
                                        <div class="answer-content" v-if="['单选题', '多选题'].includes(question.type)">
                                            {{ formatChoiceAnswer(question.answer) }}
                                        </div>
                                        <div class="answer-content" v-else>
                                            {{ question.answer }}
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <!-- 题库选择对话框 -->
        <el-dialog
            v-model="questionBankDialogVisible"
            title="选择题库"
            width="30%"
            :close-on-click-modal="false"
        >
            <el-select v-model="selectedQuestionBank" placeholder="请选择题库" style="width: 100%">
                <el-option
                    v-for="item in questionBanks"
                    :key="item.questionName"
                    :label="item.questionName"
                    :value="item.questionName"
                />
            </el-select>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="questionBankDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="showQuestionSelectionDialog">
                        下一步
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 试题选择对话框 -->
        <el-dialog
            v-model="questionSelectionDialogVisible"
            title="选择试题"
            width="80%"
            :close-on-click-modal="false"
        >
            <div class="question-selection">
                <el-table
                    :data="questions"
                    style="width: 100%"
                    border
                    stripe
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="type" label="题型" width="100">
                        <template #default="scope">
                            <el-tag size="small" :type="getQuestionTypeTag(scope.row.type)">
                                {{ scope.row.type }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="content" label="题目内容" min-width="300" show-overflow-tooltip />
                    <el-table-column prop="difficulty" label="难度" width="80">
                        <template #default="scope">
                            <el-tag size="small" :type="getDifficultyTag(scope.row.difficulty)">
                                {{ scope.row.difficulty }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="分值" width="120">
                        <template #default="scope">
                            <el-input-number
                                v-model="scope.row.score"
                                :min="1"
                                :max="100"
                                size="small"
                                style="width: 100px"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="预览" width="80">
                        <template #default="scope">
                            <el-button type="primary" link @click="previewQuestion(scope.row)">
                                预览
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="questionSelectionDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddQuestions">
                        添加选中试题
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 试题预览对话框 -->
        <el-dialog
            v-model="previewDialogVisible"
            title="试题预览"
            width="50%"
            :close-on-click-modal="false"
        >
            <div v-if="currentPreviewQuestion" class="question-preview">
                <div class="preview-header">
                    <el-tag size="small" :type="getQuestionTypeTag(currentPreviewQuestion.type)">
                        {{ currentPreviewQuestion.type }}
                    </el-tag>
                    <el-tag size="small" :type="getDifficultyTag(currentPreviewQuestion.difficulty)" class="ml-2">
                        {{ currentPreviewQuestion.difficulty }}
                    </el-tag>
                </div>
                
                <div class="preview-content">
                    <div class="content-text">{{ currentPreviewQuestion.content }}</div>
                    
                    <!-- 选择题选项 -->
                    <div v-if="['单选题', '多选题'].includes(currentPreviewQuestion.type)" class="options">
                        <template v-if="currentPreviewQuestion.options">
                            <div v-for="(option, idx) in parseOptions(currentPreviewQuestion.options)" 
                                 :key="idx" 
                                 class="option-item"
                                 v-show="option">
                                <span class="option-label">{{ String.fromCharCode(65 + idx) }}.</span>
                                <span class="option-content">{{ option }}</span>
                            </div>
                        </template>
                    </div>
                    
                    <div class="preview-answer">
                        <div class="answer-label">参考答案：</div>
                        <div class="answer-content" v-if="['单选题', '多选题'].includes(currentPreviewQuestion.type)">
                            {{ formatChoiceAnswer(currentPreviewQuestion.answer) }}
                        </div>
                        <div class="answer-content" v-else>
                            {{ currentPreviewQuestion.answer }}
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 添加试题对话框 -->
        <el-dialog
            v-model="addQuestionDialogVisible"
            title="添加试题"
            width="50%"
        >
            <el-form :model="newQuestion" :rules="questionRules" ref="questionFormRef" label-width="100px">
                <el-form-item label="题目内容" prop="content">
                    <el-input
                        v-model="newQuestion.content"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入题目内容"
                    />
                </el-form-item>
                <el-form-item label="分值" prop="score">
                    <el-input-number
                        v-model="newQuestion.score"
                        :min="1"
                        :max="100"
                        placeholder="请输入分值"
                    />
                </el-form-item>
                <el-form-item label="答案" prop="answer">
                    <el-input
                        v-model="newQuestion.answer"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入答案"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addQuestionDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddQuestion">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Plus, Delete } from '@element-plus/icons-vue';
import examApi from '@/api/exam';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const examFormRef = ref(null);
const loading = ref(false);
const tableKey = ref(0);

// 对话框控制
const questionBankDialogVisible = ref(false);
const questionSelectionDialogVisible = ref(false);
const previewDialogVisible = ref(false);
const currentPreviewQuestion = ref(null);

// 数据
const questionBanks = ref([]);
const questions = ref([]);
const selectedQuestionBank = ref('');
const selectedQuestions = ref([]);

// 添加试题对话框控制
const addQuestionDialogVisible = ref(false);
const questionFormRef = ref(null);
const newQuestion = ref({
    content: '',
    score: 1,
    answer: ''
});

const statusOptions = [
    { value: '待添加试题', label: '待添加试题' },
    { value: '待发布', label: '待发布' },
    { value: '待开始', label: '待开始' },
    { value: '已开始', label: '已开始' },
    { value: '已结束', label: '已结束' },
    { value: '进行中', label: '进行中' }
];

const examForm = ref({
    examId: null,
    examName: '',
    subject: '',
    startTime: '',
    duration: 0,
    totalScore: 0,
    status: '',
    teacherId: '',
    questionList: []
});

// 是否可以添加试题
const canAddQuestions = computed(() => {
    return examForm.value.status === '待添加试题';
});

// 是否有试题
const hasQuestions = computed(() => {
    return examForm.value.questionList && examForm.value.questionList.length > 0;
});

const rules = {
    examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
    subject: [{ required: true, message: '请输入考试科目', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
    totalScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

const questionRules = {
    content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
    score: [{ required: true, message: '请输入分值', trigger: 'blur' }],
    answer: [{ required: true, message: '请输入答案', trigger: 'blur' }]
};

// 获取考试详情
const fetchExamDetail = async () => {
    loading.value = true;
    try {
        const response = await examApi.getExamDetail(route.params.id);
        console.log('API返回的原始数据:', response);
        if (response.code === 200) {
            const examData = response.data;
            console.log('获取到的试题列表:', examData.questionList);

            // 确保 questionList 是数组
            const questionList = Array.isArray(examData.questionList) ? examData.questionList : [];
            console.log('处理后的试题列表:', questionList);

            // 重新构建表单数据
            examForm.value = {
                examId: examData.examId,
                examName: examData.examName,
                subject: examData.subject,
                startTime: examData.startTime,
                duration: examData.duration,
                totalScore: examData.totalScore,
                teacherId: examData.teacherId,
                status: examData.status,
                questionList: questionList
            };

            // 强制表格重新渲染
            tableKey.value += 1;

            // 使用 nextTick 确保数据更新后再检查
            await nextTick();
            console.log('更新后的表单数据:', examForm.value);
            console.log('更新后的试题列表:', examForm.value.questionList);
            console.log('试题列表长度:', examForm.value.questionList.length);
        } else {
            ElMessage.error(response.message || '获取考试详情失败');
        }
    } catch (error) {
        console.error('获取考试详情失败:', error);
        ElMessage.error('获取考试详情失败');
    } finally {
        loading.value = false;
    }
};

// 获取题库列表
const showQuestionBankDialog = async () => {
    try {
        // 使用 examForm 中的 teacherId
        const teacherId = examForm.value.teacherId;
        if (!teacherId) {
            ElMessage.error('未找到教师信息');
            return;
        }

        const response = await examApi.getQuestionBanks(teacherId);
        if (response.code === 200) {
            questionBanks.value = response.data;
            questionBankDialogVisible.value = true;
        } else {
            ElMessage.error(response.message || '获取题库列表失败');
        }
    } catch (error) {
        console.error('获取题库列表失败:', error);
        ElMessage.error('获取题库列表失败');
    }
};

// 显示试题选择对话框
const showQuestionSelectionDialog = async () => {
    if (!selectedQuestionBank.value) {
        ElMessage.warning('请选择题库');
        return;
    }
    try {
        const response = await examApi.getQuestionsByBank(selectedQuestionBank.value);
        if (response.code === 200) {
            // 过滤掉已经添加的试题
            const existingQuestionIds = examForm.value.questionList.map(q => q.questionId);
            questions.value = response.data
                .filter(q => !existingQuestionIds.includes(q.questionId))
                .map(q => ({ ...q, score: 1 }));
            
            if (questions.value.length === 0) {
                ElMessage.warning('该题库中的试题已全部添加');
                return;
            }
            
            questionSelectionDialogVisible.value = true;
            questionBankDialogVisible.value = false;
        } else {
            ElMessage.error(response.message || '获取试题列表失败');
        }
    } catch (error) {
        console.error('获取试题列表失败:', error);
        ElMessage.error('获取试题列表失败');
    }
};

// 处理试题选择变化
const handleSelectionChange = (selection) => {
    selectedQuestions.value = selection;
};

// 预览试题
const previewQuestion = (question) => {
    currentPreviewQuestion.value = question;
    previewDialogVisible.value = true;
};

// 添加选中的试题
const handleAddQuestions = async () => {
    if (selectedQuestions.value.length === 0) {
        ElMessage.warning('请选择要添加的试题');
        return;
    }
    
    try {
        // 构造请求数据
        const requestData = {
            examId: examForm.value.examId,
            questions: selectedQuestions.value.map(q => ({
                questionId: q.questionId,
                score: q.score
            }))
        };

        // 调用后端接口
        const response = await examApi.addExamQuestions(requestData);
        
        if (response.code === 200) {
            // 添加新选择的试题到前端列表
            examForm.value.questionList = [
                ...examForm.value.questionList,
                ...selectedQuestions.value
            ];
            
            // 关闭对话框并清空选择
            questionSelectionDialogVisible.value = false;
            selectedQuestionBank.value = '';
            selectedQuestions.value = [];
            
            ElMessage.success('添加试题成功');
        } else {
            ElMessage.error(response.message || '添加试题失败');
        }
    } catch (error) {
        console.error('添加试题失败:', error);
        ElMessage.error('添加试题失败');
    }
};

// 删除试题
const handleDeleteQuestion = (question) => {
    ElMessageBox.confirm('确定要删除这道试题吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const response = await examApi.deleteExamQuestion({
                examId: examForm.value.examId,
                questionId: question.questionId
            });
            
            if (response.code === 200) {
                examForm.value.questionList = examForm.value.questionList.filter(q => q.questionId !== question.questionId);
                ElMessage.success('删除试题成功');
            } else {
                ElMessage.error(response.message || '删除试题失败');
            }
        } catch (error) {
            console.error('删除试题失败:', error);
            ElMessage.error('删除试题失败');
        }
    }).catch(() => {});
};

// 获取题型对应的标签类型
const getQuestionTypeTag = (type) => {
    const types = {
        '单选题': 'success',
        '多选题': 'warning',
        '判断题': 'info',
        '填空题': 'primary',
        '问答题': 'danger'
    };
    return types[type] || 'info';
};

// 获取难度对应的标签类型
const getDifficultyTag = (difficulty) => {
    const types = {
        '易': 'success',
        '中': 'warning',
        '难': 'danger'
    };
    return types[difficulty] || 'info';
};

// 解析选项字符串为数组
const parseOptions = (optionsStr) => {
    try {
        return JSON.parse(optionsStr);
    } catch (e) {
        console.error('解析选项失败:', e);
        return [];
    }
};

// 格式化选择题答案
const formatChoiceAnswer = (answer) => {
    if (!answer) return '';
    return answer.split('').join('、');
};

// 显示添加试题对话框
const showAddQuestionDialog = () => {
    newQuestion.value = {
        content: '',
        score: 1,
        answer: ''
    };
    addQuestionDialogVisible.value = true;
};

// 添加试题
const handleAddQuestion = async () => {
    if (!questionFormRef.value) return;
    
    await questionFormRef.value.validate((valid) => {
        if (valid) {
            // 添加新试题到列表
            examForm.value.questionList.push({
                ...newQuestion.value,
                questionId: Date.now() // 临时ID
            });
            
            addQuestionDialogVisible.value = false;
            ElMessage.success('添加试题成功');
        }
    });
};

// 提交表单
const handleSubmit = async () => {
    if (!examFormRef.value) return;
    
    await examFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            try {
                const response = await examApi.updateExam(examForm.value);
                if (response.code === 200) {
                    ElMessage.success('更新成功');
                    router.back();
                } else {
                    ElMessage.error(response.message || '更新失败');
                }
            } catch (error) {
                console.error('更新考试信息失败:', error);
                ElMessage.error('更新失败');
            } finally {
                loading.value = false;
            }
        }
    });
};

// 重置表单
const resetForm = () => {
    if (examFormRef.value) {
        examFormRef.value.resetFields();
    }
};

// 返回上一页
const goBack = () => {
    router.back();
};

onMounted(() => {
    fetchExamDetail();
});
</script>

<style scoped>
.edit-exam {
    padding: 20px;
}

.edit-card {
    max-width: 1000px;
    margin: 0 auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h2 {
    margin: 0;
}

.edit-content {
    padding: 20px 0;
}

.questions-section {
    margin-top: 30px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.question-actions {
    display: flex;
    gap: 10px;
}

.section-header h3 {
    margin: 0;
    color: #333;
}

:deep(.el-form-item) {
    margin-bottom: 22px;
}

:deep(.el-date-picker) {
    width: 100%;
}

.question-selection {
    max-height: 500px;
    overflow-y: auto;
}

.question-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.question-card {
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.question-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-bottom: 1px solid #ebeef5;
}

.question-index {
    font-weight: bold;
    color: #333;
}

.question-score {
    color: #ff6b6b;
    font-weight: bold;
}

.question-content {
    padding: 16px;
}

.content-text {
    margin-bottom: 16px;
    line-height: 1.6;
}

.question-answer {
    background-color: #f8f9fa;
    padding: 12px;
    border-radius: 4px;
}

.answer-label {
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 8px;
}

.answer-content {
    color: #333;
}

.delete-btn {
    margin-left: auto;
}

.preview-header {
    margin-bottom: 16px;
}

.preview-content {
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.preview-answer {
    margin-top: 16px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.ml-2 {
    margin-left: 8px;
}
</style>